package sg.org.scs.splashawards.AbstractDAO;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import sg.org.scs.splashawards.hibernateFactory.HibernateFactory;

public class AbstractDAO {
	
	private Session session;

	public Session getSession() {
		return session;
	}

	private Transaction tx;

	public AbstractDAO() {
		HibernateFactory.buildIfNeeded();
	}

	protected void startOperation() throws HibernateException {
		session = HibernateFactory.openSession();
		tx = session.beginTransaction();

	}

	protected void saveOrUpdate(Object obj) {
		try {
			startOperation();
			session.saveOrUpdate(obj);
			tx.commit();
		} catch (HibernateException e) {
			
		} finally {
			HibernateFactory.close(session);
		}
	}

	protected void save(Object obj) {
		try {
			startOperation();
			session.save(obj);
			tx.commit();
		} catch (HibernateException e) {
			handleException(e);
		} finally {
			HibernateFactory.close(session);
		}
	}

	private void handleException(HibernateException e) {
		
		
	}
	
	protected Object getEntity(Class clazz,int id){
		startOperation();
		Object obj = session.get(clazz, id);
		tx.commit();
		return obj;
	}
}
